export const bluetooth = {
  // 封装蓝牙适配器API为Promise风格
  adapterState: () => {
    return new Promise((resolve, reject) => {
      uni.getBluetoothAdapterState({
        success: (res) => resolve(res),
        fail: (err) => {
          uni.showModal({
            title: '请确认手机蓝牙是否打开',
            showCancel: false,
          })
          reject(new Error('获取蓝牙适配器状态失败:' + err.errMsg))
        },
      })
    })
  },
  getDevices: () => {
    return new Promise((resolve, reject) => {
      uni.getBluetoothDevices({
        success: (res) => resolve(res),
        fail: (err) => reject(new Error('获取蓝牙设备列表失败:' + err.errMsg)),
      })
    })
  },
  stopDiscovery: () => {
    return new Promise((resolve, reject) => {
      uni.stopBluetoothDevicesDiscovery({
        success: (res) => resolve(res),
        fail: (err) => reject(new Error('停止搜索蓝牙设备失败:' + err.errMsg)),
      })
    })
  },
  closeAdapter: () => {
    return new Promise((resolve, reject) => {
      uni.closeBluetoothAdapter({
        success: (res) => {
          console.log('关闭蓝牙成功')
          uni.$off(uni.$myNotifyEventName)
          resolve(res)
        },
        fail: (err) => reject(new Error('蓝牙适配器关闭失败:' + err.errMsg)),
      })
    })
  },
  openAdapter: () => {
    return new Promise((resolve, reject) => {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log('初始化蓝牙成功', res)
          resolve(res)
        },
        fail: (err) => {
          //设备已经连接
          if (err.errMsg === 'openBluetoothAdapter:fail already opened') {
            console.log('errMsg', err.errMsg)
            resolve()
          }
          reject(new Error('蓝牙初始化失败:' + err.errMsg))
        },
      })
    })
  },

  startDiscovery: (options) => {
    return new Promise((resolve, reject) => {
      uni.startBluetoothDevicesDiscovery({
        ...options,
        success: resolve,
        fail: reject,
      })
    })
  },

  createConnection: (device) => {
    return new Promise((resolve, reject) => {
      console.log('device', device)
      uni.createBLEConnection({
        // deviceId: devId.deviceId,
        ...device,
        success: (res) => {
          uni.showToast({
            title: '设备连接成功',
            icon: 'fails',
            duration: 1000,
          })
          console.log('设备连接成功', res)
          resolve(device)
        },
        fail: (err) => {
          //重复点击该设备
          if (err.errMsg === 'createBLEConnection:fail already connect') {
            console.log('errMsg', err.errMsg)
            resolve(device.deviceId)
          }
          uni.showToast({
            title: '设备接失败',
            icon: 'fails',
            duration: 1000,
          })
          console.log(err)
          reject(new Error('设备连接失败:' + err.errMsg))
        },
      })
    })
  },

  getServices: (deviceId) => {
    return new Promise((resolve, reject) => {
      uni.getBLEDeviceServices({
        deviceId,
        success: (res) => {
          resolve(res)
          console.log(res)
        },
        fail: (err) => {
          console.log(err)
          reject(err)
        },
      })
    })
  },

  getCharacteristics: (deviceId, serviceId) => {
    return new Promise((resolve, reject) => {
      uni.getBLEDeviceCharacteristics({
        deviceId,
        serviceId,
        success: (res) => {
          // console.log(res)
          resolve(res)
        },
        fail: reject,
      })
    })
  },

  writeValue: (opts, value) => {
    return new Promise((resolve, reject) => {
      uni.writeBLECharacteristicValue({
        ...opts.write,
        value,
        // success: resolve,
        // fail: reject,
        success: (res) => {
          console.log('success  指令发送成功', value)
          resolve(res)
          // uni.showToast({
          //   title: '发送指令成功',
          //   icon: 'fails',
          //   duration: 100,
          // })
          // console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        },
        fail: (err) => {
          reject(err)
          uni.showToast({
            title: 'write 连接失败',
            icon: 'fails',
            duration: 1000,
          })
          console.log(err)
        },
      })
    })
  },

  notify: (opts, state) => {
    return new Promise((resolve, reject) => {
      uni.notifyBLECharacteristicValueChange({
        ...opts.notify,
        // state: true,
        state,
        // success: resolve,
        // fail: reject,
        success: (res) => {
          resolve(res)
          uni.showToast({
            title: '开始监听',
            icon: 'fails',
            duration: 1000,
          })
          console.log('listenNotify：', res)
          // console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        },
        fail: (err) => {
          reject(err)
          uni.showToast({
            title: '监听失败',
            icon: 'fails',
            duration: 1000,
          })
          console.log('listen err', e)
        },
      })
    })
  },

  closeConnection: (deviceId) => {
    return new Promise((resolve, reject) => {
      uni.closeBLEConnection({
        deviceId,
        success: (res) => {
          console.log(res)
          resolve
        },
        fail: (err) => {
          console.log(err.errMsg)
          reject
        },
      })
    })
  },
}

// 监听器的管理封装
export const bluetoothListeners = {
  onDeviceFound: (callback) => {
    uni.onBluetoothDeviceFound(callback)
    return () => uni.offBluetoothDeviceFound(callback)
  },

  onCharacteristicValueChange: (callback) => {
    uni.onBLECharacteristicValueChange(callback)
    // return () => uni.offBLECharacteristicValueChange(callback)
    // uni.off('BLECharacteristicValueChange')
  },

  onAdapterStateChange: (callback) => {
    uni.onBluetoothAdapterStateChange(callback)
    return () => uni.offBluetoothAdapterStateChange(callback)
  },
}
